package com.molichuxing.services.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.molichuxing.services.business.service.ResourceBizService;
import com.molichuxing.services.infrastructure.dto.response.response.AccountDto;
import com.molichuxing.services.infrastructure.dto.response.response.AccountGroupDto;
import com.molichuxing.services.infrastructure.dto.response.response.GroupResourceDto;
import com.molichuxing.services.infrastructure.dto.response.response.ResourceDto;
import com.molichuxing.services.infrastructure.service.AccountGroupService;
import com.molichuxing.services.infrastructure.service.AccountService;
import com.molichuxing.services.infrastructure.service.GroupResourceService;
import com.molichuxing.services.infrastructure.service.ResourceService;
import com.molichuxing.services.property.SystemTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限组合服务
 *
 * @author zoumingyu
 * @date 2019年9月9日
 */
@Service("resourceBizService")
public class ResourceBizServiceImpl implements ResourceBizService {
    private static final Logger logger = LoggerFactory.getLogger(ResourceBizServiceImpl.class);

    @Resource
    private AccountService accountService;

    @Resource
    private AccountGroupService accountGroupService;

    @Resource
    private GroupResourceService groupResourceService;

    @Resource
    private ResourceService resourceService;

    /**
     * 获取op左侧菜单树
     *
     * @param accountId
     * @return
     */
    @Override
    public List<ResourceDto> getMenuTree(Integer accountId) {
        logger.error("获取菜单树入参 accountId ::{}", accountId);
        if (accountId == null || accountId <= 0) {
            throw new IllegalArgumentException("invalid param accountId is " + accountId);
        }

        AccountDto account = accountService.getById(accountId);
        if (account == null) {
            throw new NullPointerException("account is null");
        }

        List<ResourceDto> result = null;

        if (account.getSystemType().getValue() == SystemTypeEnum.DEALER.getValue() && account.getIsSuper()) { //当前登录用户为超级管理员
            Map<String, Object> getResourceParm = new HashMap<String, Object>();
            getResourceParm.put("systemType", SystemTypeEnum.DEALER.getValue());
            result = editorTree(resourceService.getResourceListByParam(getResourceParm));
        } else {
            //查询用户和角色关联表
            Map<String, Object> getAccountGroupParam = new HashMap();
            getAccountGroupParam.put("accountId", account.getId());
            List<AccountGroupDto> accountGroupList = accountGroupService.getAccountGroupListByParam(getAccountGroupParam);
            logger.error("获取菜单树,用户绑定的角色 ::{}", JSON.toJSONString(accountGroupList));
            if (CollectionUtils.isNotEmpty(accountGroupList)) {
                AccountGroupDto accountGroup = accountGroupList.get(0);

                final List<Integer> resourceIds = new ArrayList<>();

                //查询角色与权限的关联表
                Map<String, Object> getGroupResourceParam = new HashMap<>();
                getGroupResourceParam.put("groupId", accountGroup.getGroupId());
                List<GroupResourceDto> groupResourceList = groupResourceService.getGroupResourceListByParm(getGroupResourceParam);
                if (CollectionUtils.isNotEmpty(groupResourceList)) {
                    groupResourceList.forEach(groupResource -> {
                        resourceIds.add(groupResource.getResourceId()); //将角色拥有的权限id放入集合
                    });
                }

                logger.error("获取菜单树,用户拥有的权限id集合 ::{}", JSON.toJSONString(resourceIds));

                //查询用户所拥有的权限
                if (CollectionUtils.isNotEmpty(resourceIds)) {
                    Map<String, Object> getResourceMap = new HashMap<>();
                    getResourceMap.put("ids", resourceIds);
                    result = editorTree(resourceService.getResourceListByParam(getResourceMap));
                }
            }
        }

        return result;
    }

    private List<ResourceDto> editorTree(List<ResourceDto> dataList) {
        final List<ResourceDto> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataList.forEach(data -> {
                if (data.getPid() == 0) {
                    result.add(data);
                }
            });

            if (CollectionUtils.isNotEmpty(result)) {
                result.forEach(firstLevel -> {
                    editorTree(firstLevel, dataList);
                });
            }
        }
        return result;
    }

    private void editorTree(ResourceDto dto, List<ResourceDto> dataList) {
        final List<ResourceDto> children = new ArrayList<>();
        if (dto.getPermissionId() == 246) {
            System.out.println(1);
        }
        dto.setChildren(children);
        for (ResourceDto data : dataList) {
            int permissionId = dto.getPermissionId();
            if (data.getPid() == permissionId) {
                children.add(data);
                editorTree(data, dataList);
            }
        }
    }
}
